<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="title"
    width="600px"
    :minHeight="100"
    :showContinueBtn="showContinueBtn"
    :continueText="continueText"
    cancelText="取消"
    okText="确定"
    @ok="handleSubmit(0)"
    @continue="handleSubmit(1)"
    :closeFunc="onClose">
    <template #insertFooter>
      <a-space :size="10" v-if="dataForm.id" class="float-left">
        <a-button :disabled="getPrevDisabled" @click="handlePrev">上一条</a-button>
        <a-button :disabled="getNextDisabled" @click="handleNext">下一条</a-button>
      </a-space>
    </template>
    <a-row class="dynamic-form">
      <a-form
        :colon="false"
        size="default"
        layout="horizontal"
        labelAlign="right"
        :labelCol="{ style: { width: '100px' } }"
        :model="dataForm"
        :rules="dataRule"
        ref="formRef">
        <a-row :gutter="15">
          <!-- 具体表单 -->

          <a-col :span="24" class="ant-col-item">
            <a-tabs v-model:activeKey="activecnbnut" tabPosition="top" class="mb-20">
              <a-tab-pane tab="Tab 1" key="1" forceRender></a-tab-pane>
            </a-tabs>
            <a-col :span="24" class="ant-col-item">
              <a-form-item name="starttime">
                <template #label>审批时间</template>
                <JnpfDatePicker
                  v-model:value="dataForm.starttime"
                  @change="changeData('starttime', -1)"
                  placeholder="请选择"
                  :allowClear="true"
                  :style="{ width: '100%' }"
                  format="YYYY-MM-DD"
                  :startTime="getRelationDate(false, 1, 1, '', '')"
                  :endTime="getRelationDate(false, 1, 1, '', '')">
                </JnpfDatePicker>
              </a-form-item>
            </a-col>
            <a-col :span="24" class="ant-col-item">
              <a-form-item name="reporting_unit">
                <template #label>上报单位</template>
                <JnpfInput
                  v-model:value="dataForm.reporting_unit"
                  @change="changeData('reporting_unit', -1)"
                  placeholder="请输入"
                  :allowClear="true"
                  :style="{ width: '100%' }">
                </JnpfInput>
              </a-form-item>
            </a-col>
            <a-col :span="24" class="ant-col-item">
              <a-form-item name="projects_nums">
                <template #label>项目数量</template>
                <JnpfInput
                  v-model:value="dataForm.projects_nums"
                  @change="changeData('projects_nums', -1)"
                  placeholder="请输入"
                  :allowClear="true"
                  :style="{ width: '100%' }">
                </JnpfInput>
              </a-form-item>
            </a-col>
            <a-col :span="24" class="ant-col-item">
              <a-form-item name="engineering">
                <template #label>工程</template>
                <JnpfInput
                  v-model:value="dataForm.engineering"
                  @change="changeData('engineering', -1)"
                  placeholder="请输入"
                  :allowClear="true"
                  :style="{ width: '100%' }">
                </JnpfInput>
              </a-form-item>
            </a-col>
            <a-col :span="24" class="ant-col-item">
              <a-form-item name="goods">
                <template #label>货物</template>
                <JnpfInput v-model:value="dataForm.goods" @change="changeData('goods', -1)" placeholder="请输入" :allowClear="true" :style="{ width: '100%' }">
                </JnpfInput>
              </a-form-item>
            </a-col>
            <a-col :span="24" class="ant-col-item">
              <a-form-item name="service">
                <template #label>服务</template>
                <JnpfInput
                  v-model:value="dataForm.service"
                  @change="changeData('service', -1)"
                  placeholder="请输入"
                  :allowClear="true"
                  :style="{ width: '100%' }">
                </JnpfInput>
              </a-form-item>
            </a-col>
            <a-col :span="24" class="ant-col-item">
              <a-form-item name="rentOut">
                <template #label>租赁</template>
                <JnpfInput
                  v-model:value="dataForm.rentOut"
                  @change="changeData('rentOut', -1)"
                  placeholder="请输入"
                  :allowClear="true"
                  :style="{ width: '100%' }">
                </JnpfInput>
              </a-form-item>
            </a-col>
            <a-col :span="24" class="ant-col-item">
              <a-form-item name="other">
                <template #label>其他</template>
                <JnpfInput v-model:value="dataForm.other" @change="changeData('other', -1)" placeholder="请输入" :allowClear="true" :style="{ width: '100%' }">
                </JnpfInput>
              </a-form-item>
            </a-col>
          </a-col>
          <!-- 表单结束 -->
        </a-row>
      </a-form>
    </a-row>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { create, update, getInfo } from './helper/api';
  import { reactive, toRefs, nextTick, ref, unref, computed } from 'vue';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { JnpfRelationForm } from '/@/components/Jnpf';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStore } from '/@/store/modules/user';
  import type { FormInstance } from 'ant-design-vue';
  import { thousandsFormat, getDateTimeUnit, getTimeUnit } from '/@/utils/jnpf';
  import { getDictionaryDataSelector } from '/@/api/systemData/dictionary';
  import { getDataInterfaceRes } from '/@/api/systemData/dataInterface';
  import dayjs from 'dayjs';
  // 表单权限
  import { usePermission } from '/@/hooks/web/usePermission';

  interface State {
    dataForm: any;
    tableRows: any;
    dataRule: any;
    optionsObj: any;
    childIndex: any;
    isEdit: any;
    interfaceRes: any;
    //可选范围默认值
    ableAll: any;
    title: string;
    continueText: string;
    allList: any[];
    currIndex: number;
    isContinue: boolean;
    submitType: number;
    showContinueBtn: boolean;
  }

  const emit = defineEmits(['reload']);
  const userStore = useUserStore();
  const userInfo = userStore.getUserInfo;
  const { createMessage, createConfirm } = useMessage();
  const [registerModal, { openModal, setModalProps }] = useModal();
  const formRef = ref<FormInstance>();
  const state = reactive<State>({
    dataForm: {
      starttime: undefined,
      reporting_unit: undefined,
      projects_nums: undefined,
      engineering: undefined,
      goods: undefined,
      service: undefined,
      rentOut: undefined,
      other: undefined,
    },

    tableRows: {},

    dataRule: {},

    optionsObj: {},

    childIndex: -1,
    isEdit: false,
    interfaceRes: { projects_nums: [], other: [], service: [], rentOut: [], goods: [], starttime: [], engineering: [], reporting_unit: [] },
    //可选范围默认值
    ableAll: {},

    title: '',
    continueText: '',
    allList: [],
    currIndex: 0,
    isContinue: false,
    submitType: 0,
    showContinueBtn: true,
  });
  const { title, continueText, showContinueBtn, dataRule, dataForm, optionsObj, ableAll } = toRefs(state);

  const getPrevDisabled = computed(() => state.currIndex === 0);
  const getNextDisabled = computed(() => state.currIndex === state.allList.length - 1);
  // 表单权限
  const { hasFormP } = usePermission();

  defineExpose({ init });
  const activecnbnut = ref('1'); //初始化tab值

  function init(data) {
    state.isContinue = false;
    state.title = !data.id ? '新增' : '编辑';
    state.continueText = !data.id ? '确定并新增' : '确定并继续';
    setFormProps({ continueLoading: false });
    state.dataForm.id = data.id;
    openModal();
    state.allList = data.allList;
    state.currIndex = state.allList.length && data.id ? state.allList.findIndex(item => item.id === data.id) : 0;
    nextTick(() => {
      getForm().resetFields();
      setTimeout(initData, 0);
    });
  }
  function initData() {
    changeLoading(true);
    if (state.dataForm.id) {
      getData(state.dataForm.id);
    } else {
      //初始化options

      // 设置默认值
      state.dataForm = {
        starttime: undefined,
        reporting_unit: undefined,
        projects_nums: undefined,
        engineering: undefined,
        goods: undefined,
        service: undefined,
        rentOut: undefined,
        other: undefined,
      };
      state.childIndex = -1;
      changeLoading(false);
    }
  }
  function getForm() {
    const form = unref(formRef);
    if (!form) {
      throw new Error('form is null!');
    }
    return form;
  }
  function getData(id) {
    getInfo(id).then(res => {
      state.dataForm = res.data || {};

      state.childIndex = -1;
      changeLoading(false);
    });
  }
  async function handleSubmit(type) {
    try {
      const values = await getForm()?.validate();
      if (!values) return;
      state.submitType = type;
      state.submitType === 1 ? setFormProps({ continueLoading: true }) : setFormProps({ confirmLoading: true });
      const formMethod = state.dataForm.id ? update : create;
      formMethod(state.dataForm)
        .then(res => {
          createMessage.success(res.msg);
          state.submitType === 1 ? setFormProps({ continueLoading: false }) : setFormProps({ confirmLoading: false });
          if (state.submitType == 1) {
            initData();
            state.isContinue = true;
          } else {
            setFormProps({ visible: false });
            emit('reload');
          }
        })
        .catch(() => {
          state.submitType === 1 ? setFormProps({ continueLoading: false }) : setFormProps({ confirmLoading: false });
        });
    } catch (_) {}
  }
  function handlePrev() {
    state.currIndex--;
    handleGetNewInfo();
  }
  function handleNext() {
    state.currIndex++;
    handleGetNewInfo();
  }
  function handleGetNewInfo() {
    changeLoading(true);
    getForm().resetFields();
    const id = state.allList[state.currIndex].id;
    getData(id);
  }
  function setFormProps(data) {
    setModalProps(data);
  }
  function changeLoading(loading) {
    setModalProps({ loading });
  }
  async function onClose() {
    if (state.isContinue) emit('reload');
    return true;
  }

  function changeData(model, index) {
    state.isEdit = false;
    state.childIndex = index;
    for (let key in state.interfaceRes) {
      if (key != model) {
        let faceReList = state.interfaceRes[key];
        for (let i = 0; i < faceReList.length; i++) {
          let relationField = faceReList[i].relationField;
          if (relationField) {
            let modelAll = relationField.split('-');
            let faceMode = '';
            for (let i = 0; i < modelAll.length; i++) {
              faceMode += modelAll[i];
            }
            if (faceMode == model) {
              let options = 'get' + key + 'Options';
              eval(options)(true);
              changeData(key, index);
            }
          }
        }
      }
    }
  }
  function changeDataFormData(type, data, model, index, defaultValue) {
    if (!state.isEdit) {
      if (type == 2) {
        for (let i = 0; i < state.dataForm[data].length; i++) {
          if (index == -1) {
            state.dataForm[data][i][model] = defaultValue;
          } else if (index == i) {
            state.dataForm[data][i][model] = defaultValue;
          }
        }
      } else {
        state.dataForm[data] = defaultValue;
      }
    }
  }
  function getRelationDate(timeRule, timeType, timeTarget, timeValueData, dataValue) {
    let timeDataValue: any = null;
    let timeValue = Number(timeValueData);
    if (timeRule) {
      if (timeType == 1) {
        timeDataValue = timeValue;
      } else if (timeType == 2) {
        timeDataValue = dataValue;
      } else if (timeType == 3) {
        timeDataValue = new Date().getTime();
      } else if (timeType == 4 || timeType == 5) {
        const type = getTimeUnit(timeTarget);
        const method = timeType == 4 ? 'subtract' : 'add';
        timeDataValue = dayjs()[method](timeValue, type).valueOf();
      }
    }
    return timeDataValue;
  }
  function getRelationTime(timeRule, timeType, timeTarget, timeValue, formatType, dataValue) {
    let format = formatType == 'HH:mm' ? 'HH:mm:00' : formatType;
    let timeDataValue: any = null;
    if (timeRule) {
      if (timeType == 1) {
        timeDataValue = timeValue || '00:00:00';
        if (timeDataValue.split(':').length == 3) {
          timeDataValue = timeDataValue;
        } else {
          timeDataValue = timeDataValue + ':00';
        }
      } else if (timeType == 2) {
        timeDataValue = dataValue;
      } else if (timeType == 3) {
        timeDataValue = dayjs().format(format);
      } else if (timeType == 4 || timeType == 5) {
        const type = getTimeUnit(timeTarget + 3);
        const method = timeType == 4 ? 'subtract' : 'add';
        timeDataValue = dayjs()[method](timeValue, type).format(format);
      }
    }
    return timeDataValue;
  }
</script>
